<template>
  <app-dialog-form
    :title="props.ruleItem ? '编辑商品规格' : '添加商品规格'"
    :confirm="handleSubmit"
    :width="950"
    @closed="handleDialogClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item
        label="规格模板名称"
        prop="rule_name"
      >
        <el-input
          v-model="formData.rule_name"
          style="width: 200px;"
          placeholder="请输入标题名称"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.spec.length > 0"
        label=""
      >
        <template
          v-for="(item, index) in formData.spec"
          :key="index"
        >
          <div>
            <el-tag
              size="medium"
              closable
              @close="handleDeleteSpec(index)"
            >
              {{ item.value }}
            </el-tag>
          </div>
          <div>
            <el-tag
              v-for="(name, nameIndex) in item.detail"
              :key="nameIndex"
              type="info"
              size="small"
              closable
              style="margin-right: 5px;"
              @close="handleDeleteSpec(index, nameIndex)"
            >
              {{ name }}
            </el-tag>
            <el-input
              v-model="newSpecItem[index]"
              placeholder="请输入属性名称"
              clearable
              style="width: 200px;"
            >
              <template #append>
                <el-button
                  @click="handleAddNewRuleItem(index)"
                >
                  添加
                </el-button>
              </template>
            </el-input>
          </div>
        </template>
      </el-form-item>
      <template v-if="isAdding">
        <el-form
          ref="innerForm"
          inline
          :model="innerFormData"
          :rules="innerFormRules"
          label-width="120px"
        >
          <el-form-item
            label="规格名称"
            prop="addName"
          >
            <el-input
              v-model="innerFormData.addName"
              style="width: 200px;"
              placeholder="请输入规格名称"
            />
          </el-form-item>
          <el-form-item
            label="规格值"
            prop="addRule"
          >
            <el-input
              v-model="innerFormData.addRule"
              style="width: 200px;"
              placeholder="请输入规格值"
            />
          </el-form-item>
          <el-form-item label="">
            <el-button
              type="primary"
              @click="handleConfirmNewRule"
            >
              确定
            </el-button>
            <el-button
              type="default"
              @click="isAdding = false"
            >
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <template v-else>
        <el-form-item label="">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="handleAddNewRule"
          >
            添加新规格
          </el-button>
        </el-form-item>
      </template>
    </el-form>
  </app-dialog-form>
</template>

<script lang="ts" setup>
import { nextTick, ref } from 'vue'
import type { PropType } from 'vue'
import type { IElForm, IFormRule } from '@/types/element-plus'
import { ElMessage } from 'element-plus'
import { saveProductRule } from '@/api/product'
import { ProductRule } from '@/api/types/product'
import * as utils from '@/utils/utils'

interface spec {
  value: string
  detail: string[]
}

interface formDataType {
  // eslint-disable-next-line camelcase
  rule_name: string
  // eslint-disable-next-line camelcase
  rule_value: string
  spec: spec[]
}

const props = defineProps({
  ruleItem: {
    type: Object as PropType<ProductRule | null>,
    default: null
  }
})

interface EmitsType {
  (e: 'update:rule-item', value: ProductRule | null): void
  (e: 'success'): void
}

const emit = defineEmits<EmitsType>()

const form = ref<IElForm | null>(null)
const innerForm = ref<IElForm | null>(null)
const isAdding = ref(false)
const newSpecItem = ref<string[]>([])
const formData = ref<formDataType>({
  rule_name: '',
  rule_value: '',
  spec: []
})

const innerFormData = ref({
  addName: '',
  addRule: ''
})

const formRules: IFormRule = {
  rule_name: [
    { required: true, message: '请输入规格模板名称', trigger: 'blur' }
  ]
}
const innerFormRules: IFormRule = {
  addName: [
    { required: true, message: '请输入规格名称', trigger: 'blur' }
  ],
  addRule: [
    { required: true, message: '请输入规格值', trigger: 'blur' }
  ]
}

const handleDialogOpen = async () => {
  nextTick(() => {
    if (props.ruleItem) {
      formData.value = {
        rule_name: props.ruleItem.rule_name,
        rule_value: props.ruleItem.rule_value,
        spec: JSON.parse(props.ruleItem.rule_value)
      }
    }
  })
}

const handleDialogClosed = () => {
  emit('update:rule-item', null)
  formData.value.rule_name = ''
  formData.value.rule_value = ''
  formData.value.spec = []
  form.value?.clearValidate() // 清除验证结果
  innerForm.value?.clearValidate() // 清除验证结果
  innerForm.value?.resetFields() // 清除表单数据
  isAdding.value = false
  newSpecItem.value = []
}

const handleSubmit = async () => {
  const valid = await form.value?.validate()
  if (!valid) {
    return
  }
  if (formData.value.spec.length < 1) {
    return ElMessage.error('请至少添加一条规格')
  }
  const { spec } = formData.value
  formData.value.rule_value = JSON.stringify(spec)
  props.ruleItem
    ? await saveProductRule(formData.value, props.ruleItem.id)
    : await saveProductRule(formData.value, 0)
  emit('success')
  ElMessage.success('保存成功')
}

const handleAddNewRule = () => {
  isAdding.value = true
}

const handleResetInnerForm = () => {
  innerFormData.value.addName = ''
  innerFormData.value.addRule = ''
  isAdding.value = false
}

const handleConfirmNewRule = async () => {
  const valid = await innerForm.value?.validate()
  if (!valid) {
    return
  }
  const { addName, addRule } = innerFormData.value
  const { spec } = formData.value
  for (let i = 0, len = spec.length; i < len; i += 1) {
    if (spec[i].value === addName) {
      return
    }
  }
  const newSpec = {
    value: addName,
    detail: [addRule]
  }
  formData.value.spec.push(newSpec)
  newSpecItem.value.push('')
  handleResetInnerForm()
}

const handleDeleteSpec = (index: number, nameIndex?: number) => {
  const target = nameIndex !== undefined ? formData.value.spec[index].detail : formData.value.spec
  const i = nameIndex || index
  utils.arraySplice(target, i, 1)
  if (!nameIndex) {
    utils.arraySplice(newSpecItem.value, index, 1)
  }
}

const handleAddNewRuleItem = (index: number) => {
  const item = newSpecItem.value[index]
  if (!item) {
    ElMessage.error('请输入属性值')
  }
  const { detail } = formData.value.spec[index]
  if (detail.indexOf(item) === -1) {
    detail.push(item)
  }
  newSpecItem.value[index] = ''
}
</script>

<style lang="scss" scoped>
</style>
